/*
 * @Author: yt 2399493770@qq.com
 * @Date: 2023-12-29 15:01:17
 * @LastEditors: yt 2399493770@qq.com
 * @LastEditTime: 2024-04-25 23:04:59
 * @Description:
 */

import { verify, sign } from "jsonwebtoken";
import { useGetRedisValue, useRedis } from "../hooks/useRedis";
import { BasicsResult } from "../helpers/BasicsResult";
import { Request, Response } from "express";

const { NEXT_PUBLIC_ACCESS_TOKEN_SECRET } = process.env;

// 生成token 签发token

export const getToken = (data: string | object | Buffer) => {
  return sign(data, NEXT_PUBLIC_ACCESS_TOKEN_SECRET ?? ""); // expiresIn 有效时间 2h 2小时
};

/**
 * 解析token
 * 1. token 不存在
 * 2. token 解密失败 (修改 过期)
 * 3. token 有效 解密成功
 * @param req
 * @param res
 */
export function checkToken(req: Request, res: Response) {
  return new Promise((resolve, reject) => {
    const token = req.headers.tokens as string;
    if (token) {
      verify(
        token,
        NEXT_PUBLIC_ACCESS_TOKEN_SECRET ?? "",
        (err: any, data: any) => {
          if (err) {
            res.json(BasicsResult.tokenOverdue());
            return;
          }
          resolve(data);
        }
      );
    }
    res.json(BasicsResult.validateFailed("header，缺失Token"));
    reject(null);
  });
}

export function isTokenStaleDated(token: string) {
  const result = useGetRedisValue("token");
}
